package com.hducms.cms.web;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.hducms.cms.entity.main.CmsUser;
import com.hducms.cms.service.CmsUserService;
import com.hducms.common.web.ResponseUtils;
import com.hducms.common.web.session.SessionProvider;
import com.hducms.core.service.AuthenticationService;

/**
 * CMS上下文信息拦截器
 * 
 * 包括登录信息、权限信息、站点信息
 */
public class FrontContextInterceptor extends HandlerInterceptorAdapter {
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler)
					throws ServletException {

		String requestUrl = request.getRequestURI().toString();
		if (requestUrl != null && requestUrl.matches(loginUrl)) {
			return true;
		}
		CmsUser user = null;
		Integer userId = authMng.retrieveUserIdFromSession(session, request);
		if (userId != null) {
			user = cmsUserMng.findById(userId);
		}

		if (user != null) {
			CmsUtils.setUser(request, user);
			return true;
		}
		else {
			ResponseUtils.renderText(response, "NOJSESSIONID");
			return false;
		}
	}

	@Autowired
	private SessionProvider session;
	@Autowired
	private CmsUserService cmsUserMng;
	@Autowired
	private AuthenticationService authMng;
	private String loginUrl;
	@Autowired
	public void setLoginUrl(String loginUrl) {
		this.loginUrl = loginUrl;
	}

}